package com.mrper.asm.click

import org.objectweb.asm.MethodVisitor
import org.objectweb.asm.Opcodes
import org.objectweb.asm.Type
import org.objectweb.asm.commons.AdviceAdapter

class ViewClickMethodAdapter(
    api: Int,
    methodVisitor: MethodVisitor?,
    access: Int,
    name: String?,
    private val descriptor: String?,
    private val isLambdaMethod: Boolean,
) : AdviceAdapter(api, methodVisitor, access, name, descriptor) {

    override fun onMethodExit(opcode: Int) {
        super.onMethodExit(opcode)
        var viewArgTypeIndex = Type.getArgumentTypes(descriptor)
            .indexOfFirst { it.descriptor == ViewClickMethodConstants.ViewDescriptor }
        if (viewArgTypeIndex == -1) return
        // Lambda方法与类内部方法的参数序号不一样，类内部的方法的参数序号从1开始(this占用了一个序号)，而Lambda的从0开始
        viewArgTypeIndex += +(if (!isLambdaMethod) 1 else 0)
        // 方法后面追加2333333333333333333输出
        // kotlin.run {
        //     mv.visitFieldInsn(Opcodes.GETSTATIC, "java/lang/System", "out", "Ljava/io/PrintStream;")
        //     mv.visitLdcInsn("233333333333333333333333333")
        //     mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, "java/io/PrintStream", "println", "(Ljava/lang/String;)V", false)
        // }
        kotlin.run {
            mv.visitVarInsn(Opcodes.ALOAD, viewArgTypeIndex)
            mv.visitMethodInsn(Opcodes.INVOKESTATIC,
                "com/sph/ga/tool/asm/ViewClickHandler",
                "onHandleClickEvent",
                "(Landroid/view/View;)V",
                false)
        }
        // mv.visitMaxs(1, 2)
        mv.visitEnd()
    }

}